package com.tang.calculator.utils;

import com.tang.calculator.exception.ConversionException;
import com.tang.calculator.symbols.BigDecimalValueSymbol;
import com.tang.calculator.symbols.ValueSymbol;
import com.tang.calculator.symbols.ValueSymbolFactory;

import java.lang.reflect.Field;
import java.math.BigDecimal;

/**
 * @auther: zhiy
 * @date: 2021/3/22
 * @description:
 */
public class NumFormatFactory {

    public static BigDecimal format(Object obj, String field) throws Exception {
        Field f = obj.getClass().getDeclaredField(field);
        if (f == null) throw new ConversionException("配有匹配到字段");
        f.setAccessible(true);
        Object fv = f.get(obj);
        if (fv instanceof Short) {
            return ValueSymbolFactory.create(((Short) fv).toString()).getValue();
        } else if (fv instanceof Long) {
            return ValueSymbolFactory.create(((Long) fv).toString()).getValue();
        } else if (fv instanceof Double) {
            return ValueSymbolFactory.create( fv.toString()).getValue();
        } else if (fv instanceof Integer) {
            return ValueSymbolFactory.create( fv.toString()).getValue();
        } else if (fv instanceof BigDecimal){
            return ValueSymbolFactory.create( fv.toString()).getValue();
        } else if (fv instanceof String) {
            ValueSymbol valueSymbol = ValueSymbolFactory.create((String) fv);
            if(valueSymbol instanceof BigDecimalValueSymbol) return valueSymbol.getValue();
            return ValueSymbolFactory.createString((String)fv).getValue();
        }else {
            throw new ConversionException("计算器不支持该数据类型" + fv.getClass().toString());
        }
    }
}
